import router from "@/router/index.js"
import { userStore } from '@/stores/user.js'

const user = userStore()

const changeRouterKeepAlive = (name, state, componentName) => {
  const keepAliveInclude = user.keepAliveInclude
  const setKeepAliveInclude = (item) => {
    if (item.name === name) {
      if (state) {
        user.setKeepAliveInclude([...keepAliveInclude, componentName])
      } else {
        const temp = keepAliveInclude.filter(item => item !== componentName)
        user.setKeepAliveInclude(temp)
      }
    }
  }
  router.options.routes.map((item) => {
    setKeepAliveInclude(item)
    item.children?.map((ite) => {
      setKeepAliveInclude(ite)
    })
  })
}

const determineNeedSaveKeepALive = (to, from, needSaveRoute, componentName) => {
  if (Array.isArray(needSaveRoute)) {
    if (needSaveRoute.includes(to.name)) {
      changeRouterKeepAlive(from.name, true, componentName)
      return
    }
  }
  if (to.name === needSaveRoute) {
    changeRouterKeepAlive(from.name, true, componentName)
    return
  }
  changeRouterKeepAlive(from.name, false, componentName)
}

export { determineNeedSaveKeepALive }
